package com.dp.service.companymanage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.service.impl3.BaseImpl;
import com.dp.util.DataMap;
import com.dp.util.KeyGenerator;
import com.dp.vo.TRoles;

@Service
@Transactional
public class RoleServiceImpl extends BaseImpl {
	
	/**
	 * 
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return
	 */
	public List<TRoles> findAllRole(DataMap hashMap, Integer firstrow, Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
        String role_name = (String)hashMap.get("role_name");
		StringBuffer sqlS = new StringBuffer("select role_id,role_name,role_type from t_roles");
		if(role_name!=null&&role_name.trim().length() > 0){
			sqlS.append(" where role_name like '%" + role_name + "%'");
		}
		
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord());
			}
		}
		
		if (firstrow != null && maxrow != null) {
			sqlS.append(" limit "+firstrow+","+maxrow);
		}
		List<TRoles> result = new ArrayList<TRoles>();;
		try {
			logger.info("findAllRole excute sql:"+sqlS.toString());
			Query query = em.createNativeQuery(sqlS.toString());
			List<Object[]> l = query.getResultList();
			if(l.size()>0)
			{
				for (Object[] objects : l) 
				{
					if (objects != null && objects.length > 0) 
					{
						int j = 0;
						TRoles one = new TRoles();
						one.setRoleId((String)objects[j++]);
						one.setRoleName((String)objects[j++]);
						one.setRoleType(ObjectToString(objects[j++]));
						result.add(one);
					}
				}
			}
		} catch (Exception e) {
			logger.error("findAllRole error!!!"+e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获得所有角色总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public int findAllRoleCount(DataMap hashMap){
		int iCount = 0; 
        String role_name = (String)hashMap.get("role_name");
		StringBuffer sqlS = new StringBuffer("select count(role_id) from t_roles");
		if(role_name!=null&&role_name.trim().length() > 0){
			sqlS.append(" where role_name like '%" + role_name + "%'");
		}
		sql=sqlS.toString();
		try {
			iCount=this.getOneInt();
//			this.init();
//			logger.info("findAllRoleCount excute sql:"+sqlS.toString());
//			this.rs1=stmt.executeQuery(sqlS.toString());
//			if(this.rs1.next())
//				iCount=rs1.getInt(1);
//			this.closeAll();
		} catch (Exception e) {
			logger.error("findAllRoleCount fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return iCount;
	}
	
	public boolean checkRoleName(String roleName)
	{
		boolean t = false;
		try {
//			this.init();
			sql=("select count(role_name) as totalrow from t_roles where role_name='"+roleName+"'");
//			rs1.next();
//			if(!"0".equals(rs1.getString(1))) 
				t= (this.getOneInt()>0);
		}
		catch (Exception e) {
			logger.error("checkRoleName fail !!!" + e.getMessage());
			e.printStackTrace();
		}
//		finally{this.closeAll(); }
		return t;
	}
	
	public boolean insertRole(TRoles role)
	{
        String role_id = KeyGenerator.getInstance().getNextKeyValue("t_roles");
        role.setRoleId(role_id);
        try {
			return this.execUpdate("insert into t_roles(role_id,role_name,role_type) VALUES('" + role_id + "','" + role.getRoleName() + "'," +
					"'" + role.getRoleType() + "')");
		} catch (Exception e) {
			logger.error("insertRole fail !!!" + e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	/*public boolean updateRole(TRoles role)
	{
        String role_id = KeyGenerator.getInstance().getNextKeyValue("t_roles");
        try {
			return this.execUpdate("update t_roles set role_name='" + role.getRoleName() + "',role_type='"
					+ role.getRoleType() + "' where role_id ='" + role_id + "'");
		} catch (Exception e) {
			logger.error("insertRole fail !!!" + e.getMessage());
			e.printStackTrace();
			return false;
		}
	}*/
	
	/**
	 * 删除角色
	 * @param hashMap
	 * @return 如果返回null，则已给用户分配该角色，即不能删除。
	 */
    public Boolean deleteRole(DataMap hashMap) {
		ArrayList arrayList = null;
		try {
			sql=("select count(*) from t_user where role_id='" + hashMap.get("role_id") + "'");
			if(this.getOneInt()>0)return null;
//			if(arrayList.size() > 0) return null;
		} catch (Exception e1) {
			e1.printStackTrace();
			return false;
		}
//		String sql = "delete from t_user_auth where user_id in(";
//		for (int i = 0; i < arrayList.size(); i++) {
//			hashMap = (DataMap) arrayList.get(i);
//			sql = sql + "'" + hashMap.get("user_id") + "',";
//		}
//		sql = sql + "'safsafsafsafsa')";
//		String[] sqls = new String[3];
//		sqls[0] = sql;
		sql = "delete from t_role_menu where role_id ='" + hashMap.get("role_id") + "'";
		this.em.createNativeQuery(sql).executeUpdate();
		sql = "delete from t_roles where role_id ='" + hashMap.get("role_id") + "'";
		this.em.createNativeQuery(sql).executeUpdate();
		try {
//			return execTransaction(sqls);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

    public ArrayList getRolename1List(DataMap hm) {
        ArrayList aNode1 = new ArrayList();
        String sql =
            "select n2.mainmenu_id from t_role_menu ra,t_submenus n2 where n2.is_use='Y' and ra.submenu_id=n2.submenu_id and ra.role_id='" +
            hm.get("role_id") + "'";
        try {
            aNode1 = queryALLResultSet(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aNode1;
    }

    public ArrayList getRolename2List(DataMap hm) {
        ArrayList aNode2 = new ArrayList();
        String sql = "select submenu_id from t_role_menu where role_id='" +
            hm.get("role_id") + "'";
        try {
            aNode2 = queryALLResultSet(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aNode2;
    }
    
    public Vector getNodeList() {
        ArrayList sAl = new ArrayList();
        ArrayList mAl = new ArrayList();
        DataMap sHm = new DataMap();
        DataMap mHm = new DataMap();
        int sNum = 0;
        int mNum = 0;

        //查询节点一的信息
        String serviceSql = "select mainmenu_id,mainmenu_name,is_use,is_open,ctrl_date,action,orderid from t_mainmenus where is_use='Y' order by mainmenu_id";

        //查询某角色下的某用户拥有的菜单项信息 （可以将该SQL修改后创建为视图，方便查询）
        String moduleSql = "select submenu_id,mainmenu_id,submenu_name,ctrl_url,is_use,ctrl_date,target,action,request,orderid" +
        		" from t_submenus where is_use='Y' order by mainmenu_id";
        Vector vAuth = new Vector();

        try {
           sAl = queryALLResultSet(serviceSql);
            mAl = queryALLResultSet(moduleSql);
            sNum = sAl.size();
            mNum = mAl.size();

            for (int i = 0; i < sNum; i++) //一级菜单
             {
                Vector vS = new Vector();
                sHm = (DataMap) sAl.get(i);

                String s_node1_id = sHm.get("mainmenu_id").toString().trim();
                boolean isPutService = false;

                for (int k = 0; k < mNum; k++) //二级菜单
                 {
                    mHm = (DataMap) mAl.get(k);

                    String m_node1_id = mHm.get("mainmenu_id").toString().trim();
                    String m_node2_id = mHm.get("submenu_id").toString().trim();

                    if (m_node1_id.equals(s_node1_id)) {
                        if (!isPutService) {
                            vS.addElement(sHm);
                            isPutService = true;
                        }

                        vS.addElement(mHm);
                    }
                }

                if (vS.size() > 0) {
                    vAuth.addElement(vS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vAuth;
    }
    
    //修改角色
    public boolean RoleManageEdit(DataMap hm) {
        ArrayList arrayListSql = new ArrayList();
        ArrayList t_user_auth_sql = new ArrayList();
        DataMap hashMap = null;
        ArrayList arrayList = null;
        boolean isTrue = false;
        //String role_auth_id = null;
       // String user_auth_id = null;
        String sql = null;

        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String str = hm.get("gvalue").toString();
        String split = "|";
        StringTokenizer token = new StringTokenizer(str, split);
        String[] sqlBatch;

        //删除 角色(岗位)配置字典表 特定数据
       

        int i = 0;

        try {
            arrayList = queryALLResultSet("select user_id,employee_id,role_id,ctrl_date,user_pwd,auth_tupe,can_access,code" +
            		" from t_user where role_id='" + hm.get("role_id") + "'");

            //删除 用户权限表 特定数据 
            //删除这样角色的用户的原来的从角色继承的权限
            sql = "delete from t_user_auth where user_id in(";
            i = 0;

            for (i = 0; i < arrayList.size(); i++) {
                hashMap = (DataMap) arrayList.get(i);
                sql = sql + "'" + hashMap.get("user_id") + "',";
            }

            sql = sql + "'safsafsafsafsa')";
            
            sql+=" and submenu_id in (select submenu_id from t_role_menu where role_id='" +   hm.get("role_id") + "')";
            
            arrayListSql.add(sql);
            arrayListSql.add("delete from t_role_menu where role_id='" + hm.get("role_id") + "'");
            i = 1;

            List<String> needadd=new ArrayList<String>();//需要增加的权限
            String temp_submenu="";
            
            //添加 角色(岗位)配置字典表 特定数据
            while (token.hasMoreTokens()) {
                //role_auth_id = KeyGenerator.getInstance().getNextKeyValue("t_role_auth");
            	temp_submenu=token.nextToken();
                //user_auth_id = KeyGenerator.getInstance().getNextKeyValue("t_user_auth");
                sql = "insert into t_role_menu (role_id,submenu_id) values('" +
                   hm.get("role_id") + "','" +temp_submenu + "')";

                // t_user_auth_sql.add("insert into t_user_auth (user_auth_id,employee_id,node2_id,ctrl_date) values('" + user_auth_id + "','" + hashMap.get("employee_id")+ "','" + token.nextToken() + "','" + nowTime + "')");                
                arrayListSql.add(sql);
                needadd.add(temp_submenu);

                //i++;
            }

            //添加 用户权限表 特定数据
            i = 1;
            //user_auth_id = KeyGenerator.getInstance().getNextKeyValue("t_user_auth");

           

            //组合sql        
            for (i = 0; i < t_user_auth_sql.size(); i++) {
                arrayListSql.add(t_user_auth_sql.get(i));
            }

            sqlBatch = new String[arrayListSql.size()];

            for (i = 0; i < arrayListSql.size(); i++) {
                sqlBatch[i] = this.ObjectToString(arrayListSql.get(i));
                

                //System.out.println(sqlBatch[i]);
            }

            isTrue = execTransaction(sqlBatch);
            
            //首先查出用户已经具有的，而且是本次角色已经增加的，然后从新增中去除，在加入用户权限表，防止重复
            sql = "select user_id,submenu_id from t_user_auth where user_id in(";
            for (i = 0; i < arrayList.size(); i++) {
                hashMap = (DataMap) arrayList.get(i);
                sql = sql + "'" + hashMap.get("user_id") + "',";
            }

            sql = sql + "'safsafsafsafsa')";            
            sql+=" and submenu_id in ( ";
            for(String s:needadd)
            {
            	sql+="'"+s+"',";
            }
            sql+="'ss')";
            System.out.println(sql);
           List<DataMap> has=null;// queryALLResultSet(sql);
           
          
           t_user_auth_sql.clear();
            String user_id="";
            String submenu="";
            boolean need=true;
            for (int i1 = 0; i1 < arrayList.size(); i1++) {
                user_id = ((DataMap) arrayList.get(i1)).getMapData("user_id");                
                for(String s:needadd)
                {
                	need=true;
                    for(DataMap da:has)
                    {
                    	if(user_id.equals(da.getMapData("user_id"))&& s.equals(da.getMapData("submenu_id")))
                    	{
                    		need=false;
                    		break;  
                    	}
                    }
                    if(need) t_user_auth_sql.add(
                    		"insert into t_user_auth (user_id,submenu_id) values('" + user_id+ "','" + s +"')");
                }
                //token = new StringTokenizer(str, split);

           }
            sqlBatch = new String[t_user_auth_sql.size()];
            for (i = 0; i < t_user_auth_sql.size(); i++) {
                sqlBatch[i] = this.ObjectToString(t_user_auth_sql.get(i));
            }
            execTransaction(sqlBatch);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTrue;
    }
//    private String ObjectToString(Object param){
//    	return param==null ? "" : param.toString().trim();
//    }
    
    
    
    
	/*public UserInfo getUesrByEmpId(String emp_id)
	{
		StringBuffer sqlS = new StringBuffer("select tu.*,te.* from t_user tu,t_employee te ");
		sqlS.append(" where te.employee_id=:emp_id and tu.employee_id=te.employee_id");
		UserInfo one = new UserInfo();
		try {
			this.initEM();
			logger.info("getUesrByUserId excute sql:"+sqlS.toString());
			Query query = em.createNativeQuery(sqlS.toString());
			query.setParameter("emp_id", emp_id);
			List<Object[]> list = query.getResultList();
			this.closeAll();
			Object[] objects = list.get(0);
			if (objects != null && objects.length > 0) 
			{
				int j = 0;
				one.setUser_id((String)objects[j++]);
				one.setEmployee_id((String)objects[j++]);
				one.setRole_id((String)objects[j++]);
				j++;//ctrl date
				one.setUser_pwd((String)objects[j++]);
				j++;//auth tupe
				Boolean canaccess = (Boolean)objects[j++];
				one.setCan_access(canaccess==true?1:0);
				j++;//te.employeeid
				one.setSp_code((String)objects[j++]);
				one.setEmployee_name((String)objects[j++]);
				one.setEmployee_phone((String)objects[j++]);
				one.setEmployee_email((String)objects[j++]);
				j++;//leader
				one.setJob((String)objects[j++]);
				one.setInfo((String)objects[j++]);
			}
		}catch (Exception e) {
			logger.error("getUesrByUserId error!!!"+e.getMessage());
			e.printStackTrace();
		}finally{
			this.closeAll();
		}
		return one;
	}*/
	
	/*public int updateUser(UserInfo user,String user_pwddd)
	{
		//0成功1失败2已存在
		int t = 0;
		String user_id = this.ObjectToStringDB(user.getUser_id());
		String role_id = this.ObjectToStringDB(user.getRole_id());
		String user_pwd = this.ObjectToStringDB(MD5.StringMD5(user.getUser_pwd()));
		String can_access = this.ObjectToStringDB(user.getCan_access());
		//emp
		String employee_id = this.ObjectToStringDB(user.getEmployee_id());
		String sp_code = this.ObjectToStringDB(user.getSp_code());
		String employee_name = this.ObjectToStringDB(user.getEmployee_name());
		String employee_phone = this.ObjectToStringDB(user.getEmployee_phone());
		String employee_email = this.ObjectToStringDB(user.getEmployee_email());
		String job = this.ObjectToStringDB(user.getJob());
		String info = this.ObjectToStringDB(user.getInfo());
		
		List<String> subMenuList = new ArrayList<String>();
		try {
			this.init();
			rs1=stmt.executeQuery("select submenu_id from t_role_menu where role_id="+role_id);
			while(rs1.next())
			{
				String o = this.ObjectToStringDB(rs1.getString(1));
				subMenuList.add(o);
			}
			this.sql = "update t_user set role_id="+role_id+",can_access="+can_access+" where user_id="+user_id;
			if(user_pwddd != null && !"".equals(user_pwddd))
				this.sql = "update t_user set role_id="+role_id+",user_pwd="+user_pwd+",can_access="+can_access+" where user_id="+user_id;
			
			logger.info("updateUser excute sql1:"+sql);
			stmt.addBatch(sql);
			
			this.sql = "update t_employee set sp_code="+sp_code+",employee_name="+employee_name+",employee_phone="+employee_phone+
				",employee_email="+employee_email+",job="+job+",info="+info+" where employee_id="+employee_id;
			logger.info("updateUser excute sql2:"+sql);
			stmt.addBatch(sql);
	
			if(subMenuList.size()>0)
			{
				this.sql = "delete from t_user_auth where user_id="+user_id;
				stmt.addBatch(sql);
				for(String o:subMenuList)
				{
					this.sql = "insert into t_user_auth (submenu_id,user_id) values( "+o+","+user_id+")";
					stmt.addBatch(sql);
				}
			}
			stmt.executeBatch();
			conn.commit();
			this.closeAll();
		} catch (Exception e) {
			logger.error("insertUser fail !!!" + e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
		}
		finally{this.closeAll(); }
		return t;
	}*/
	
	/*public Object getSingleResult(Query query) {
		Object o =null;
		try {
			o = query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		} catch (NonUniqueResultException ex) {
			o = query.getResultList();
			return ((List) o).get(0);
		}
		return o;
	}*/
	/*public static boolean StringIsNotNull(Object str) {
        boolean b = false;
        try {
            if (!str.equals("") && !str.equals("null")) {
                b = true;
            }
        } catch (Exception e) {
        }
        return b;
    }*/
	/*private String ObjectToStringDB(Object obj) {
        try {
            String str = obj.toString().trim();
            if (str.equals("") || str.equals("null")) {
                return "null";
            }
            return "'" + str + "'";
        } catch (Exception e) {
            return "null";
        }
    }*/
}
